package com.jinzhi.jzweb.service.impl.draw;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jinzhi.common.base.CoreServiceImpl;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.dao.StuSignUpComDao;
import com.jinzhi.jzweb.dao.TrackDrawDao;
import com.jinzhi.jzweb.domain.JiangXiTrackDrawVO;
import com.jinzhi.jzweb.domain.StuSignUpComDO;
import com.jinzhi.jzweb.domain.TrackDrawDO;
import com.jinzhi.jzweb.service.draw.FuZhouDrawService;
import com.jinzhi.jzweb.service.draw.JiangXiDrawService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class JiangXiDrawServiceImpl extends CoreServiceImpl<TrackDrawDao, TrackDrawDO> implements JiangXiDrawService {

    @Autowired
    private StuSignUpComDao stuSignUpComDao;

    /**
     * 查询上一次抽签结果
     * @return
     */
    @Override
    public TrackDrawDO trackList() {
        TrackDrawDO resultVO = new TrackDrawDO();
        resultVO.setHasDraw(true);

        // 查询上一次的抽签结果
        Wrapper<TrackDrawDO> wrapper = new EntityWrapper<>();
//        wrapper.orderBy("sort", true);
        List<TrackDrawDO> trackDrawDOS = this.selectList(wrapper);

        List<JiangXiTrackDrawVO> trackDrawVOList = new ArrayList<>();

        if(trackDrawDOS != null && !trackDrawDOS.isEmpty()) {
            // 有抽签数据，按照每行三个学校的格式重组
            for (int i = 0; i < trackDrawDOS.size(); i += 3) {
                JiangXiTrackDrawVO vo = new JiangXiTrackDrawVO();

                // 第一个学校
                if (i < trackDrawDOS.size()) {
                    TrackDrawDO school1 = trackDrawDOS.get(i);
                    vo.setUnitName1(school1.getUnitName());
                    vo.setRecordNumber1(school1.getRecordNumber());
                }

                // 第二个学校
                if (i + 1 < trackDrawDOS.size()) {
                    TrackDrawDO school2 = trackDrawDOS.get(i + 1);
                    vo.setUnitName2(school2.getUnitName());
                    vo.setRecordNumber2(school2.getRecordNumber());
                }

                // 第三个学校
                if (i + 2 < trackDrawDOS.size()) {
                    TrackDrawDO school3 = trackDrawDOS.get(i + 2);
                    vo.setUnitName3(school3.getUnitName());
                    vo.setRecordNumber3(school3.getRecordNumber());
                }

                trackDrawVOList.add(vo);
            }
        } else {
            // 没有抽签数据，初始化默认数据
            resultVO.setHasDraw(false);
            List<StuSignUpComDO> stuSignUpComDOS = stuSignUpComDao.selectList(new EntityWrapper<StuSignUpComDO>().orderBy("id", true));
            if(stuSignUpComDOS != null && !stuSignUpComDOS.isEmpty()) {
                Map<String, List<StuSignUpComDO>> trackDrawByUnitMap = stuSignUpComDOS.stream()
                        .collect(Collectors.groupingBy(StuSignUpComDO::getUnitName));

                List<String> schoolList = new ArrayList<>(trackDrawByUnitMap.keySet());

                // 按每3个学校一组创建JiangXiTrackDrawVO
                for (int i = 0; i < schoolList.size(); i += 3) {
                    JiangXiTrackDrawVO vo = new JiangXiTrackDrawVO();
                    if (i < schoolList.size()) vo.setUnitName1(schoolList.get(i));
                    if (i + 1 < schoolList.size()) vo.setUnitName2(schoolList.get(i + 1));
                    if (i + 2 < schoolList.size()) vo.setUnitName3(schoolList.get(i + 2));
                    trackDrawVOList.add(vo);
                }
            }
        }

        resultVO.setTrackDrawVOList(trackDrawVOList);
        return resultVO;
    }

    /**
     * 参赛学校抽签
     * @return
     */
    @Override
    public Result<?> schoolDraw() {
        List<StuSignUpComDO> signList = stuSignUpComDao.selectList(new EntityWrapper<StuSignUpComDO>().orderBy("id", true));
        if(signList==null || signList.isEmpty()) return Result.fail("暂无选手信息");

        // 对同一院校的选手分组
        Map<String, List<StuSignUpComDO>> trackDrawByUnitMap = signList.stream()
                .collect(Collectors.groupingBy(StuSignUpComDO::getUnitName));

        int schoolCount = trackDrawByUnitMap.size();

        // 平等分配：每组基础数量
        int baseSize = schoolCount / 3;
        int remainder = schoolCount % 3; // 余数

        // 分配余数：多1个给A，多2个给A和B各1个
        int groupASize = baseSize + (remainder >= 1 ? 1 : 0);
        int groupBSize = baseSize + (remainder >= 2 ? 1 : 0);
        int groupCSize = baseSize;

        // 生成A、B、C三组的序号列表
        List<String> groupAList = new ArrayList<>();
        List<String> groupBList = new ArrayList<>();
        List<String> groupCList = new ArrayList<>();

        for (int i = 1; i <= groupASize; i++) {
            groupAList.add("A" + i);
        }
        for (int i = 1; i <= groupBSize; i++) {
            groupBList.add("B" + i);
        }
        for (int i = 1; i <= groupCSize; i++) {
            groupCList.add("C" + i);
        }

        // 合并所有序号（按A、B、C顺序）
        List<String> allNumList = new ArrayList<>();
        allNumList.addAll(groupAList);
        allNumList.addAll(groupBList);
        allNumList.addAll(groupCList);

        Random random = new Random();

        // 先复制一份用于随机分配
        List<String> randomNumList = new ArrayList<>(allNumList);
        Collections.shuffle(randomNumList, random);

        // 临时存储每个学校的抽签结果
        List<TrackDrawDO> tempList = new LinkedList<>();
        int sortOrder = 0;

        // 为每个学校分配抽签序号
        for (String schoolName : trackDrawByUnitMap.keySet()) {
            TrackDrawDO trackDrawDO = new TrackDrawDO();
            trackDrawDO.setUnitName(schoolName);
            trackDrawDO.setRecordNumber(randomNumList.get(0));
            randomNumList.remove(0);

            // 根据分配的序号在原始有序列表中的位置设置sort
            String recordNumber = trackDrawDO.getRecordNumber();
            int indexInOrderedList = allNumList.indexOf(recordNumber);
            trackDrawDO.setSort(indexInOrderedList + 1); // 从1开始排序

            tempList.add(trackDrawDO);
        }

        // 按照sort排序，确保A、B、C组的顺序
//        tempList.sort(Comparator.comparingInt(TrackDrawDO::getSort));

        // 重新组织为每行三个学校的格式，使用JiangXiTrackDrawVO
        List<JiangXiTrackDrawVO> resultList = new LinkedList<>();
        int groupSort = 1;

        for (int i = 0; i < tempList.size(); i += 3) {
            JiangXiTrackDrawVO vo = new JiangXiTrackDrawVO();

            // 第一个学校
            if (i < tempList.size()) {
                TrackDrawDO school1 = tempList.get(i);
                vo.setUnitName1(school1.getUnitName());
                vo.setRecordNumber1(school1.getRecordNumber());
            }

            // 第二个学校
            if (i + 1 < tempList.size()) {
                TrackDrawDO school2 = tempList.get(i + 1);
                vo.setUnitName2(school2.getUnitName());
                vo.setRecordNumber2(school2.getRecordNumber());
            }

            // 第三个学校
            if (i + 2 < tempList.size()) {
                TrackDrawDO school3 = tempList.get(i + 2);
                vo.setUnitName3(school3.getUnitName());
                vo.setRecordNumber3(school3.getRecordNumber());
            }

            resultList.add(vo);
        }

        // 清空之前的抽签记录并保存新的（如果需要保存到数据库）
        this.delete(new EntityWrapper<TrackDrawDO>());

        if(!tempList.isEmpty()){
            this.insertBatch(tempList);
        }

        return Result.ok(resultList);
    }


}
